package cn.ijero.pictureselector.demo;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

class PictureListPreviewAdapter extends RecyclerView.Adapter<PictureListPreviewAdapter.ViewHolder> {

    private final List<String> data = new ArrayList<>();
    private OnClickItemListener listener = null;

    @NonNull
    @Override
    public PictureListPreviewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_picture_main, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull PictureListPreviewAdapter.ViewHolder holder, int position) {
        int adapterPosition = holder.getAdapterPosition();
        String item = data.get(adapterPosition);

        ImageView imageView = holder.imageView;

        if (item == null || item.isEmpty()) {
            imageView.setImageResource(R.drawable.ic_add);
        } else {
            imageView.setImageResource(R.mipmap.test);
        }

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.onClickItem(item, adapterPosition);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public void setData(List<String> data) {
        this.data.clear();
        this.data.addAll(data);
        notifyItemRangeChanged(0, data.size());
    }

    public void setOnClickItemListener(OnClickItemListener listener) {
        this.listener = listener;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        ImageView imageView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.image_view);
        }

    }

    interface OnClickItemListener {
        void onClickItem(String item, int position);
    }

}
